define(['./../directive/tabs', './../directive/vtabs', './../service/loadMap', './../service/mapInstance', './../service/chartsFactory', './../service/toggleSideBar', './../model/modelTransform', './../model/project', './../service/webSocket/webSocketReceiver', , './../service/webSocket/webSocketEmitter', './../service/loadProjectMap', './../directive/filterProject', './../directive/singlePointQuery', './../service/viewMode'],
    function() {
        var app = angular.module('App.home');
        app.controller('homeCtrl', ['$scope', 'loadMap', 'Project', 'mapInstance', '$timeout', 'toggleSideBar', '$rootScope', 'modelTransform', 'webSocketReceiver', 'webSocketEmitter', 'loadProjectMap', '$window', '$filter', '$location', 'fullScreen', 'viewMode', 'chartsFactory',
            function($scope, loadMap, Project, mapInstance, $timeout, toggleSideBar, $rootScope, modelTransform, webSocketReceiver, webSocketEmitter, loadProjectMap, $window, $filter, $location, fullScreen, viewMode, chartsFactory) {

                webSocketReceiver.initial(); //start web socket client;
                webSocketReceiver.buffer.id = 123;


                fullScreen.initial(); //初始化全屏






                $scope.viewState = 'map';
                $rootScope.curPrj = null;
                $scope.toggleLeftSideBar = toggleSideBar.toggleLeftSideBar;
                $scope.toggleBottomSideBar = toggleSideBar.toggleBottomSideBar;

                $scope.chart = null;

                $scope.$on('mapViewSateChanged', function(event, args) {
                    $scope.viewState = args;
                });




                $scope.loadMap = function(type) {
                    //start to load projects ,inital then map
                    Project.getAllProjects(type).then(function(prjs) {
                        $rootScope.projects = [];
                        $rootScope.allPrjsByLine = [];
                        if (prjs[0].constructor.prototype.findAutoSurveyPoint) {

                        } else {
                            Project[Project.curType + 'Projects'] = prjs = modelTransform(prjs);
                        }

                        $rootScope.projects = prjs;
                        //筛选出来的工程结果的个数
                        $rootScope.filterMatchedPrjCount = $rootScope.projects.length;
                        $rootScope.allPrjsByLine = Project.allPrjsByLine;
                        return loadMap(prjs); // start to load map
                    }).then(function() {
                        return $scope.toggleLeftSideBar($rootScope.smallScreen ? 'hide' : 'show');
                    }).then(function() {
                        $timeout(function() {
                            $('#projectTypes').dropdown();
                            window.localStorage.setItem('projectType', type || 'MetroMonitor');
                        }, 0);
                    });
                };


                $scope.loadMap();
                $scope.reloadMap = function() {

                    $rootScope.$broadcast('clearFilter', null);
                    $scope.toggleBottomSideBar('hide');
                    if ($scope.viewState === 'active') {
                        $timeout(function() {
                            // $scope.loadMap();
                            loadMap($rootScope.projects);
                        }, 400);
                    } else if ($scope.viewState === 'map') {
                        return;
                    } else {

                    }

                    $scope.viewState = 'map';
                };

                //用户点击筛选按钮以后,发布show panel事件
                $scope.filterProjectClick = function() {
                    $rootScope.$broadcast("filterProjectClick", null);
                };
                //筛选选项
                $scope.searchOption = {
                    name: '',
                    mPrjLevel: '',
                    mState: '',
                    mConstructionCorp: ''
                };

                //筛选线路
                $scope.filterLineSearch = function(line) {
                    var count = 0;
                    line.projects.forEach(function(prj) {
                        var match = $scope.filterSearch(prj);
                        if (match) {
                            count++;
                        }
                    });
                    return count > 0 ? true : false;
                };
                //筛选工程
                $scope.filterSearch = function(prj) {
                    var result = true;
                    for (var property in $scope.searchOption) {
                        if ($scope.searchOption.hasOwnProperty(property)) {
                            if (property === 'name') {
                                result = prj.name.indexOf($scope.searchOption[property]) > -1 ? true : false;
                            } else {
                                if ($scope.searchOption[property] === '') {
                                    result = true;
                                } else {
                                    result = prj[property] === $scope.searchOption[property] ? true : false;
                                }
                            }
                            //每个Property循环完就总结一次
                            if (!result) {
                                prj.matchSearch = false;
                                return false;
                            }
                        }
                    }
                    prj.matchSearch = true;
                    return result;
                };

                var botoomBar_height_2 = $('#bottomBar').height() / 2;
                $scope.selectPrj = function(select) {
                    var map = mapInstance.getMap();
                    $rootScope.projects.forEach(function(item) {
                        if (item.name === select) {
                            $rootScope.curPrj = item;
                            $rootScope.curPrj.active = true;
                        } else {
                            item.active = false;
                        }
                    });
                    // toggleSideBar.toggleLeftSideBar('hide');
                    webSocketEmitter.GetProjects(); //发送请求在线设备列表的命令
                    //获取工程概况
                    $rootScope.curPrj.getProjectSummary();
                    //获取工况时间列表
                    $rootScope.curPrj.getMainStatusTimeList();
                    //对于小屏幕手机和电脑显示器,做不同的偏移计算
                    var divOffy = $rootScope.smallScreen ? 100 : 200;
                    var a = map.containerPointToLatLng([0, botoomBar_height_2 - divOffy]);
                    var b = map.containerPointToLatLng([0, 0]);
                    var offy = a.lat - b.lat; //计算
                    if (!$rootScope.smallScreen) {
                        $rootScope.curPrj.marker.openPopup();
                        $timeout(function() {
                            map.setView([$rootScope.smallHeight ? $rootScope.curPrj.center.lat + offy / 2 : $rootScope.curPrj.center.lat,
                                $rootScope.smallScreen ? $rootScope.curPrj.center.lng : $rootScope.curPrj.center.lng
                            ]);
                            mapInstance.setMapState('project');
                        }, 600);
                    } else {
                        map.prjMarkerLayer.clearLayers();
                        map.prjMarkerLayer.addLayer($rootScope.curPrj.marker);

                        $timeout(function() {
                            map.setView([$rootScope.curPrj.center.lat + offy, $rootScope.curPrj.center.lng]);
                            mapInstance.setMapState('project');
                        }, 600);
                    }
                    //关闭filter Project
                    $rootScope.$broadcast('filterProjectClick', false);
                };

                $scope.enterPrjMap = function(prj) {
                    if (!prj.hasJsonLayer) return;
                    var map = mapInstance.getMap();
                    map.fireEvent('prjMarkerClick', {
                        prjId: prj.prjId
                    });

                };

                //打开单点的历史曲线窗口
                $scope.activePoint = function(name) {
                    openChartModal(name);
                };
                //更新时间
                $scope.updateDate = function(domId, value) {
                    var dom = $('#' + domId);
                    if (dom.length === 0) return;
                    if (value) {
                        dom.val(value);
                    } else {
                        $rootScope[domId] = dom.val();
                    }
                };



                //获取到某工程某测项的所有监测时间列表
                //这这之后,根据列表中靠前的2个时间,来初始化统计查询中input中的时间,以保证查询的默认时间段总是最近的一个月
                $scope.$on('allTimes', function(event, args) {
                    var length = args.length;
                    if (length > 0) {
                        initialDate(new Date(args[0]));
                    }
                    //初始化统计查询中2个input的时间
                    function initialDate(date) {
                        $scope.updateDate('endDate', $filter('date')(date, 'yyyy-MM-dd'));
                        $scope.updateDate('endSearchDate', $filter('date')(date, 'yyyy-MM-dd HH:mm:ss'));
                        $scope.updateDate('startSearchDate', $filter('date')(date.setMinutes(date.getMinutes() - 120), 'yyyy-MM-dd HH:mm:ss'));
                        $scope.updateDate('startDate', $filter('date')(date.setMonth(date.getMonth() - 1), 'yyyy-MM-dd'));
                    }
                    initialDate(new Date());
                });

                //自定义查询
                $scope.customSearch = function() {
                    var params = {
                        startDate: $('#startSearchDate').val(),
                        endDate: $('#endSearchDate').val(),
                        prjId: $rootScope.curPrj.prjId,
                    };
                    if (!Date.parse(params.startDate) || !Date.parse(params.endDate)) {
                        alert('日期格式不正确');
                        return;
                    }
                    var prj = $rootScope.curPrj;
                    $scope.toggleBottomSideBar('hide')
                        .then(function() {
                            return prj.getRecent2Changes(viewMode.monitorType, viewMode.location, [params.startDate, params.endDate], "1");
                        })
                        .then(function(data) {
                            $rootScope.$broadcast('selectChartPane'); //选择到chart;
                            //一系列的变化曲线
                            if (data.dataList && data.dataList.length) {
                                return chartsFactory.createPointsChartListByLocation('#chart', data);
                            } else {
                                return chartsFactory.destroy('#chart');
                            }
                        })
                        .then(function() {
                            return $scope.toggleBottomSideBar('show');
                        });
                };

                //提交统计查询
                $scope.summarySubmit = function() {
                    var summaryParams = {
                        prjId: $rootScope.curPrj.prjId,
                        name: $rootScope.curPrj.name,
                        startDate: $('#startDate').val(),
                        endDate: $('#endDate').val(),
                        monitorItems: $rootScope.curPrj.getMonitorItems()
                    };
                    window.localStorage.setItem('summaryParams', JSON.stringify(summaryParams));
                    $window.open('/summary');
                };

                //打开全景图
                $scope.panaroma = function(panaromaUrl) {
                    $window.open(panaromaUrl);
                };





            }
        ]);
    });
